#include "history.h"
#include "ui_history.h"

History::History(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::History)
{
    ui->setupUi(this);
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(dataDownSlot()));
  connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(dataDownSlot()));
    // generate some data:
    QVector<double> x(101), y(101); // initialize with entries 0..100
    for (int i=0; i<101; ++i)
    {
        x[i] = i/50.0 - 1; // x goes from -1 to 1
        y[i] = x[i]*x[i]; // let's plot a quadratic function
    }
    // create graph and assign data to it:

    ui->widget_tem->addGraph();
    //     ui->widget_tem->graph(0)->setData(x, y);
    // give the axes some labels:
    ui->widget_tem->xAxis->setLabel("时间（分钟）");
    ui->widget_tem->yAxis->setLabel("温度（度）");
    // set axes ranges, so we see all data:
    ui->widget_tem->xAxis->setRange(0, 100);
    ui->widget_tem->yAxis->setRange(0, 100);

    //       for (int i = 0; i <= 100; ++i)
    //       {
    //           xData.append(i);
    //           yData.append(i);
    // //          qDebug()<<i;
    //       }
      ui->widget_2_hum->addGraph();
        ui->widget_tem->addGraph();
    ui->widget_tem->graph(0)->setData(xData, yData);
    ui->widget_tem->replot();

}

History::~History()
{
    delete ui;
}

void History::time_down()
{
    long int begin;
    long int end;

}

void History::dataUpSlot(QByteArray buf)
{

    QString jsonString=buf;
    QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
    QDateTime xx;


    // 检查解析是否成功
    if (!doc.isNull() && doc.isObject()) {
        QJsonObject jsonObj = doc.object();//创建对象

        // 读取JSON对象中的值
        int type = jsonObj["type"].toInt();
        int key=jsonObj["key"].toInt();
        //        if(type!=4)
        //        {
        //            return ;
        //        }
        bool result = jsonObj["result"].toBool();
        QJsonArray data = jsonObj["data"].toArray();
        //获取数组个数
        int n=data.size();
        qDebug()<<n;
        // 遍历数组并输出每个对象的内容
        for (const QJsonValue &value : data) {
            QJsonObject obj = value.toObject();
            long int time = obj["time"].toString().toLong();
            QString tttt=obj["time"].toString();
            QString val = obj["val"].toString();
            qDebug() << "time:" << obj["time"].toString() << ", Val:" << val.toDouble();

            QDateTime dateTime;
          //  qint64 seconds = 1623981600; // 2021-06-18T12:00:00 UTC 的秒数

            dateTime.setMSecsSinceEpoch(time*1000);
//            qDebug()<<dateTime.toString();


            if(key==301)
            {if(val.toDouble()>1)
                {
                    xData.append(  dateTime.time().minute()+60*dateTime.time().hour());
                    qDebug()<<dateTime.time().minute()+60*dateTime.time().hour();
                    yData.append(val.toDouble());


                }




            }
            if(key==302)
            {

                xDatahum.append(  dateTime.time().minute()+60*dateTime.time().hour());
                yDatahum.append(val.toInt());


            }


        }
        ui->widget_tem->graph(0)->setData(xData, yData);
        ui->widget_tem->replot();
        ui->widget_2_hum->graph(0)->setData(xDatahum, yDatahum);
        ui->widget_2_hum->replot();
//        if(key==301)
//        {
//            ui->widget_tem->graph(0)->setData(xData, yData);
//            ui->widget_tem->replot();
//        }
//       if(key==302)
//       {    ui->widget_2_hum->graph(0)->setData(xDatahum, yDatahum);
//           ui->widget_2_hum->replot();
//       }

        //        xData.clear();
        //        yData.clear();


    } else {
        qDebug() << "Failed to parse JSON.";
    }


}

void History::dataDownSlot()
{QJsonObject address;
    QJsonObject data;
    QJsonArray limit;



    limit.append(ui->dateTimeEdit_begin->dateTime().toMSecsSinceEpoch()/1000);

    int x=ui->dateTimeEdit_begin->time().minute()+60*ui->dateTimeEdit_begin->time().hour();
    int y= ui->dateTimeEdit_2_end->time().minute()+ui->dateTimeEdit_2_end->time().hour()*60;
    limit.append(ui->dateTimeEdit_2_end->dateTime().toMSecsSinceEpoch()/1000);
    ui->widget_tem->xAxis->setRange(x ,y);
    ui->widget_2_hum->xAxis->setRange(x ,y);
    qDebug() <<"起始时间" ;
    qDebug() <<x ;
    qDebug() <<y ;


    //ui->widget_tem->xAxis->setRange(limit.at(0).toInt(), limit.at(1).toInt());
    ui->widget_tem->replot();
      ui->widget_2_hum->replot();
    address.insert("type",4);
    if(ui->pushButton == sender())
      {  data.insert("key", 301);

      }else if(ui->pushButton_2 == sender())
      {
           data.insert("key", 302);
      }


    data.insert("limit", limit);

    address.insert("data",QJsonValue(data));
    // 将QJsonObject转换为QJsonDocument
    QJsonDocument jsonDoc(address);
    // 输出JSON字符串
    QString jsonString = jsonDoc.toJson(QJsonDocument::Indented);
    qDebug() << "Serialized JSON:" << jsonString;
    // 创建一个QMQTT::Message对象
    quint16 idd = 1;
    QString topic = "/app/data/down";
    QByteArray payload = jsonString.toUtf8();
    //    QByteArray payload = jsonDoc.toBinaryData();
    quint8 qos = 1;
    bool retain = false;
    QMQTT::Message message(idd, topic, payload, qos, retain);
    GlobalVal::mqtt->publish( message);


}

